package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.oocl.dao.FavoriteDao;
import com.oocl.formV1.util.DBUtil;
import com.oocl.formV1.util.FavoriteDB;
import com.oocl.pojo.Favorite;

public class FavoriteDaoImpl implements FavoriteDao{

	@Override
	public Map<String, Integer> findAll() {
		
		String sql = "select * from favorites";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con=DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			
			rs = pst.executeQuery();
			while (rs.next()) {
				FavoriteDB.getFavorites().put(rs.getString("name"), rs.getInt("id"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return FavoriteDB.getFavorites();
	}

	@Override
	public List<Favorite> findByCustId(int custId) {
		List<Favorite> list = new ArrayList<Favorite>();
		String sql = "select f.id id, f.name name from CUSTOMERS c "
				+ "left join CUST_FAVO cf on c.id = cf.cust_id "
				+ "and c.id = ? "
				+ "left join FAVORITES f on cf.favo_id = f.id";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con=DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			pst.setInt(1, custId);
			rs = pst.executeQuery();
			while (rs.next()) {
				Favorite favo=new Favorite(rs.getInt("id"), rs.getString("name"));
				list.add(favo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return list;
	}

	
}

